package com.king.juc.unsafedemo;

import com.king.juc.atomicdemo.account.Account;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author king
 * @date 2020/12/6 0:45
 */
public class SafeDemo {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        // 获取unsafe对象
//        getSafe();

        Account.demo(new MyAtomicInteger(10000));

    }

    private static void getSafe() throws NoSuchFieldException, IllegalAccessException {
        // JDK1.8需要通过反射获取, JDK11 有 getUnsafe() 方法
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);

        // 获取域的偏移地址
        long id = unsafe.objectFieldOffset(Student.class.getDeclaredField("id"));
        long name = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));

        Student student = new Student();

        // 执行cas操作
        unsafe.compareAndSwapInt(student, id, 0, 1);
        unsafe.compareAndSwapObject(student, name, null, "张三");

        // 验证
        System.out.println(student);
    }
}
